import AsyncStorage from '@react-native-async-storage/async-storage'
import { CachedDictApi, DictData, DICT_TYPE } from '../api/dict'

/**
 * 字典管理器 - 全局单例，支持持久化缓存
 */
class DictManager {
    private static instance: DictManager
    private dictData: Map<string, DictData[]> = new Map()
    private loadingPromises: Map<string, Promise<DictData[]>> = new Map()
    private initialized = false
    private readonly STORAGE_KEY = 'app_dict_data'
    private readonly STORAGE_VERSION_KEY = 'app_dict_version'
    private readonly CURRENT_VERSION = '1.0'

    private constructor() {}

    static getInstance(): DictManager {
        if (!DictManager.instance) {
            DictManager.instance = new DictManager()
        }
        return DictManager.instance
    }

    /**
     * 初始化 - 从本地存储恢复数据
     */
    async initialize(): Promise<void> {
        if (this.initialized) return

        try {
            // 检查版本
            const storedVersion = await AsyncStorage.getItem(this.STORAGE_VERSION_KEY)
            if (storedVersion !== this.CURRENT_VERSION) {
                // 版本不匹配，清除旧数据
                await AsyncStorage.removeItem(this.STORAGE_KEY)
                await AsyncStorage.setItem(this.STORAGE_VERSION_KEY, this.CURRENT_VERSION)
            } else {
                // 恢复缓存数据
                const storedData = await AsyncStorage.getItem(this.STORAGE_KEY)
                if (storedData) {
                    const parsedData = JSON.parse(storedData)
                    this.dictData = new Map(Object.entries(parsedData))
                }
            }
        } catch (error) {
            console.warn('恢复字典缓存失败:', error)
        }

        this.initialized = true
    }

    /**
     * 持久化缓存到本地存储
     */
    private async persistCache(): Promise<void> {
        try {
            const dataObject = Object.fromEntries(this.dictData)
            await AsyncStorage.setItem(this.STORAGE_KEY, JSON.stringify(dataObject))
        } catch (error) {
            console.warn('保存字典缓存失败:', error)
        }
    }

    /**
     * 获取字典数据
     */
    async getDictData(dictType: string): Promise<DictData[]> {
        await this.initialize()

        // 如果已有缓存，直接返回
        if (this.dictData.has(dictType)) {
            return this.dictData.get(dictType)!
        }

        // 如果正在加载，返回正在进行的Promise
        if (this.loadingPromises.has(dictType)) {
            return this.loadingPromises.get(dictType)!
        }

        // 开始加载
        const loadingPromise = this.loadDictFromApi(dictType)
        this.loadingPromises.set(dictType, loadingPromise)

        try {
            const data = await loadingPromise
            this.dictData.set(dictType, data)
            // 异步持久化，不阻塞返回
            this.persistCache()
            return data
        } finally {
            this.loadingPromises.delete(dictType)
        }
    }

    /**
     * 批量获取字典数据
     */
    async getMultipleDictData(dictTypes: string[]): Promise<Record<string, DictData[]>> {
        await this.initialize()

        const result: Record<string, DictData[]> = {}
        const pendingTypes: string[] = []

        // 分离已缓存和未缓存的类型
        for (const dictType of dictTypes) {
            if (this.dictData.has(dictType)) {
                result[dictType] = this.dictData.get(dictType)!
            } else {
                pendingTypes.push(dictType)
            }
        }

        // 如果所有数据都已缓存，直接返回
        if (pendingTypes.length === 0) {
            return result
        }

        // 并行加载未缓存的数据
        const loadingPromises = pendingTypes.map(async (dictType) => {
            const data = await this.getDictData(dictType)
            return { [dictType]: data }
        })

        const loadedData = await Promise.all(loadingPromises)
        loadedData.forEach(data => Object.assign(result, data))

        return result
    }

    /**
     * 从API加载字典数据
     */
    private async loadDictFromApi(dictType: string): Promise<DictData[]> {
        try {
            return await CachedDictApi.getDictDataList(dictType)
        } catch (error) {
            console.error(`加载字典数据失败: ${dictType}`, error)
            return []
        }
    }

    /**
     * 预加载所有请假相关字典
     */
    async preloadLeaveDictionaries(): Promise<void> {
        const leaveTypes = [
            DICT_TYPE.LEAVE_TYPE,
            DICT_TYPE.PERSONAL_TYPE,
            DICT_TYPE.ACADEMIC_NATURE,
            DICT_TYPE.PERSONAL_VISIT_TYPE,
            DICT_TYPE.MARITAL_STATUS,
            DICT_TYPE.PARITY,
            DICT_TYPE.IS_PRESENTATION,
            DICT_TYPE.REPORT_TYPE,
            DICT_TYPE.IS_MULTIPLE_BIRTH,
            DICT_TYPE.IS_DYSTOCIA
        ]

        // 后台预加载，不等待完成
        this.getMultipleDictData(leaveTypes).catch(error => {
            console.warn('预加载字典数据失败:', error)
        })
    }

    /**
     * 获取字典标签
     */
    getDictLabel(dictType: string, value: string | number): string {
        const dictList = this.dictData.get(dictType) || []
        let item = dictList.find(d => d.value === value)
        
        if (!item) {
            // 尝试字符串匹配
            item = dictList.find(d => String(d.value) === String(value))
        }
        
        if (!item) {
            // 尝试数字匹配
            item = dictList.find(d => Number(d.value) === Number(value))
        }
        
        return item?.label || String(value)
    }

    /**
     * 清除缓存
     */
    async clearCache(): Promise<void> {
        this.dictData.clear()
        this.loadingPromises.clear()
        await AsyncStorage.removeItem(this.STORAGE_KEY)
    }

    /**
     * 刷新指定字典类型
     */
    async refreshDictType(dictType: string): Promise<DictData[]> {
        this.dictData.delete(dictType)
        this.loadingPromises.delete(dictType)
        return this.getDictData(dictType)
    }

    /**
     * 检查字典是否已加载
     */
    isDictLoaded(dictType: string): boolean {
        return this.dictData.has(dictType)
    }

    /**
     * 获取所有已加载的字典类型
     */
    getLoadedDictTypes(): string[] {
        return Array.from(this.dictData.keys())
    }
}

export const dictManager = DictManager.getInstance()
